package top.dreamcenter.rss.common.util;

import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;

import java.io.*;
import java.nio.charset.StandardCharsets;

/**
 * 通用XML构建模板
 */
public abstract class XMLBuilder {

    /**
     * xml树根节点
     */
    protected Element root;


    public XMLBuilder() {
        initRoot();
    }

    /**
     * 初始化根节点
     */
    protected abstract void initRoot();


    /**
     * 获取文档
     * @return xml内容
     * @throws IOException 异常抛出上层处理
     */
    public String getDocRes() throws IOException {
        XMLOutputter xmlOutputter = new XMLOutputter(Format.getPrettyFormat());
        try (StringWriter writer = new StringWriter()) {
            xmlOutputter.output(new Document(root), writer);
            return writer.toString();
        }
    }


    /**
     * 保存到路径
     * @param path 路径（含文件名称）
     * @throws IOException 异常抛出上层处理
     */
    public void saveToFile(String path) throws IOException {
        try (PrintWriter writer = new PrintWriter(new OutputStreamWriter(new FileOutputStream(path), StandardCharsets.UTF_8))){
            String docRes = getDocRes();
            writer.write(docRes);
        }
    }

}
